import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Switch, message, Form, Input, Button, Spin, Descriptions, Badge } from 'antd';
import { request } from 'umi';

// 小程序配置接口
interface AppConfig {
  appId: string;
  secret: string;
  type: string;
  name: string;
}

// 商户信息接口
interface MerchantInfo {
  id: number;
  name: string;
  status: number;
  apiKey: string;
  createdAt: string;
  updatedAt: string;
}

const Settings: React.FC = () => {
  const [disableOrderPrint, setDisableOrderPrint] = useState(false);
  const [disableCheckoutPrint, setDisableCheckoutPrint] = useState(false);
  const [appConfig, setAppConfig] = useState<AppConfig | null>(null);
  const [merchantInfo, setMerchantInfo] = useState<MerchantInfo | null>(null);
  const [loading, setLoading] = useState(false);
  const [merchantLoading, setMerchantLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [form] = Form.useForm();

  // 获取商户ID
  const merchantId = window.MERCHANT_ID;

  useEffect(() => {
    // 从 localStorage 加载设置
    const orderPrintSetting = localStorage.getItem('disableOrderPrint');
    const checkoutPrintSetting = localStorage.getItem('disableCheckoutPrint');

    if (orderPrintSetting !== null) {
      setDisableOrderPrint(JSON.parse(orderPrintSetting));
    }
    if (checkoutPrintSetting !== null) {
      setDisableCheckoutPrint(JSON.parse(checkoutPrintSetting));
    }

    // 获取小程序配置和商户信息
    fetchAppConfig();
    fetchMerchantInfo();
  }, []);

  // 获取商户信息
  const fetchMerchantInfo = async () => {
    setMerchantLoading(true);
    try {
      const response = await request(`/admin/merchant`, {
        method: 'GET',
      });

      if (response?.data) {
        setMerchantInfo(response.data);
      }
    } catch (error) {
      console.error('获取商户信息失败:', error);
      message.error('获取商户信息失败');
    } finally {
      setMerchantLoading(false);
    }
  };

  // 获取小程序配置
  const fetchAppConfig = async () => {
    setLoading(true);
    try {
      const response = await request(`/admin/merchant/appConfig`, {
        method: 'GET',
      });

      if (response?.data) {
        setAppConfig(response.data);
        form.setFieldsValue(response.data);
      }
    } catch (error) {
      console.error('获取小程序配置失败:', error);
      message.error('获取小程序配置失败');
    } finally {
      setLoading(false);
    }
  };

  // 更新小程序配置
  const updateAppConfig = async (values: AppConfig) => {
    setSubmitting(true);
    try {
      await request(`/admin/merchant/appConfig`, {
        method: 'PUT',
        data: {
          ...values,
          type: 'mini_app', // 确保类型始终为 mini_app
          appSecret: values.secret
        },
      });

      message.success('小程序配置已保存');
      setAppConfig({
        ...values,
        type: 'mini_app'
      });
    } catch (error) {
      console.error('保存小程序配置失败:', error);
      message.error('保存小程序配置失败');
    } finally {
      setSubmitting(false);
    }
  };

  const handleOrderPrintChange = (checked: boolean) => {
    setDisableOrderPrint(checked);
    localStorage.setItem('disableOrderPrint', JSON.stringify(checked));
    message.success('设置已保存');
  };

  const handleCheckoutPrintChange = (checked: boolean) => {
    setDisableCheckoutPrint(checked);
    localStorage.setItem('disableCheckoutPrint', JSON.stringify(checked));
    message.success('设置已保存');
  };

  // 格式化商户状态显示
  const renderMerchantStatus = (status: number) => {
    if (status === 1) {
      return <Badge status="success" text="正常" />;
    } else {
      return <Badge status="error" text="停用" />;
    }
  };

  return (
    <PageContainer>
      {/* 商户信息卡片 */}
      <Card title="商户信息" bordered={false} style={{ marginBottom: 24 }}>
        <Spin spinning={merchantLoading}>
          {merchantInfo ? (
            <Descriptions bordered column={2}>
              <Descriptions.Item label="商户ID">{merchantInfo.id}</Descriptions.Item>
              <Descriptions.Item label="商户名称">{merchantInfo.name}</Descriptions.Item>
              <Descriptions.Item label="商户状态">
                {renderMerchantStatus(merchantInfo.status)}
              </Descriptions.Item>
              <Descriptions.Item label="API密钥">
                {merchantInfo.apiKey || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="创建时间" span={2}>
                {merchantInfo.createdAt}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间" span={2}>
                {merchantInfo.updatedAt}
              </Descriptions.Item>
            </Descriptions>
          ) : (
            <div style={{ textAlign: 'center', padding: '20px 0' }}>暂无商户信息</div>
          )}
        </Spin>
      </Card>

      {/* 打印设置卡片 */}
      <Card title="打印设置" bordered={false} style={{ marginBottom: 24 }}>
        <div style={{ marginBottom: 24 }}>
          <div style={{ marginBottom: 16, display: 'flex', alignItems: 'center' }}>
            <Switch
              checked={disableOrderPrint}
              onChange={handleOrderPrintChange}
              checkedChildren="已禁用"
              unCheckedChildren="已启用"
            />
            <span style={{ marginLeft: 16, fontSize: 14 }}>禁用下单自动打票</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Switch
              checked={disableCheckoutPrint}
              onChange={handleCheckoutPrintChange}
              checkedChildren="已禁用"
              unCheckedChildren="已启用"
            />
            <span style={{ marginLeft: 16, fontSize: 14 }}>禁用结账自动打小票</span>
          </div>
        </div>
      </Card>

      {/* 小程序配置卡片 */}
      <Card title="小程序配置" bordered={false}>
        <Spin spinning={loading}>
          <Form
            form={form}
            layout="vertical"
            onFinish={updateAppConfig}
            initialValues={{ type: 'mini_app' }}
          >
            <Form.Item
              label="小程序名称"
              name="name"
              rules={[{ required: true, message: '请输入小程序名称' }]}
            >
              <Input placeholder="请输入小程序名称" />
            </Form.Item>

            <Form.Item
              label="AppID"
              name="appId"
              rules={[{ required: true, message: '请输入AppID' }]}
            >
              <Input placeholder="请输入AppID" />
            </Form.Item>

            <Form.Item
              label="AppSecret"
              name="secret"
              rules={[{ required: true, message: '请输入AppSecret' }]}
            >
              <Input.Password placeholder="请输入AppSecret" />
            </Form.Item>

            <Form.Item name="type" hidden>
              <Input />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={submitting}
              >
                保存配置
              </Button>
            </Form.Item>
          </Form>
        </Spin>
      </Card>
    </PageContainer>
  );
};

export default Settings;
